package ca.badenhorst.ourtrition.activity;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import ca.badenhorst.ourtrition.R;
import ca.badenhorst.ourtrition.db.DatabaseHelper;
import ca.badenhorst.ourtrition.model.FoodDescription;
import ca.badenhorst.ourtrition.model.FoodGroup;

public class SearchActivity extends Activity {

    private ListView listView;
    private TextView emptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        listView = (ListView) this.findViewById(R.id.search_list);
        emptyView = (TextView) this.findViewById(R.id.search_empty);
        emptyView.setVisibility(TextView.GONE);

        // Get the intent, verify the action and get the query
        Intent intent = getIntent();
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);
            String group = null;
            if (appData != null) {
                group = appData.getString(FoodGroup.GROUP_CODE);
            }
            String query = intent.getStringExtra(SearchManager.QUERY);
            setTitle("returning results for '"+query+"'");

            this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    itemClicked(position);
                }
            });

            new SearchListTask(group, query).execute();
        }
    }

    private void itemClicked(int position) {
        Cursor cursor = (Cursor) this.listView.getAdapter().getItem(position);
        Intent detailsIntent = new Intent(SearchActivity.this, FoodDescriptionActivity.class);
        String ndbNo = cursor.getString(1);
        detailsIntent.putExtra(FoodDescription.NDB_NO, ndbNo);
        startActivity(detailsIntent);
    }

    private class SearchListTask extends AsyncTask<Void, Void, Cursor> {

        private final String query;
        private final String groupCd;

        public SearchListTask(String group, String query) {
            this.groupCd = group;
            this.query = query;
        }

        @Override
        protected Cursor doInBackground(Void... params) {
            DatabaseHelper helper = new DatabaseHelper(SearchActivity.this);
            SQLiteDatabase db = helper.getReadableDatabase();
            StringBuilder builder = new StringBuilder("select f.id as _id, f.ndb_no, f.name from foods f, food_groups fg where f.food_group_cd=fg.groupCd");
            List<String> selectionArgs = new ArrayList<String>();
            if (!TextUtils.isEmpty(groupCd)) {
                builder.append(" and fg.description=?");
                selectionArgs.add(groupCd);
            }
            if (!TextUtils.isEmpty(query)) {
                String[] tokens = query.split(" "); // break on whitespace
                for (int i = 0; i < tokens.length; i++) {
                    builder.append(" and");
                    builder.append(" name like ?");
                    selectionArgs.add("%" + tokens[i] + "%");
                }
            }
            builder.append(" order by f.name");

            String[] args = new String[selectionArgs.size()];
            selectionArgs.toArray(args);
            return db.rawQuery(builder.toString(), args);
        }

        @Override
        protected void onPostExecute(Cursor cursor) {
            if (cursor.getCount() == 0) {
                emptyView.setVisibility(TextView.VISIBLE);
                listView.setVisibility(TextView.GONE);
            } else {
                SimpleCursorAdapter adapter = new SimpleCursorAdapter(SearchActivity.this, R.layout.list_item, cursor, new String[]{"name"}, new int[]{R.id.list_item}, 0);
                listView.setAdapter(adapter);
                emptyView.setVisibility(TextView.GONE);
                listView.setVisibility(TextView.VISIBLE);
            }
        }
    }
}
